package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.CustomerBean;
import com.project.service.ICustomerService;
import com.project.valid.AddValid;
import com.project.valid.UpdateValid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("customer")
public class CustomerController {
    @Autowired
    private ICustomerService service;
    @RequestMapping("findAll")
    public List<CustomerBean> findAll(){
        return service.findAll();
    }
    @RequestMapping("findByItem")
    public PageInfo<CustomerBean> findByItem(Integer pageNO, String name, String scope){
        return service.findByItem(pageNO, name, scope);
    }
    @RequestMapping("findById")
    public CustomerBean findByItem(int id){
        return service.findById(id);
    }
    @RequestMapping("add")
    public String add(@Validated(AddValid.class) CustomerBean customer, BindingResult result) throws JsonProcessingException {
       if(result.hasErrors()){
           return new ObjectMapper().writeValueAsString(result.getFieldErrors());
       }else {
           service.add(customer);
           return "ok";
       }
    }
    @RequestMapping("update")
    public String update(@Validated(UpdateValid.class) CustomerBean customer , BindingResult result) throws JsonProcessingException {
        if (result.hasErrors()){
            return new ObjectMapper().writeValueAsString(result.getFieldErrors());
        }else {
            service.update(customer.getId(), customer.getHeadMan(),customer.getTel() , customer.getScope());
            return "ok";
        }

    }




}
